"""
基础情感分析脚本
对评论进行基本的正负面情感分类
"""

import json
import os
import pandas as pd
from snownlp import SnowNLP
import jieba
from collections import Counter

class BasicSentimentAnalyzer:
    """基础情感分析器"""
    
    def __init__(self):
        self.sentiment_thresholds = {
            "positive": 0.6,
            "negative": 0.4
        }
    
    def analyze_sentiment(self, text):
        """
        分析单条文本的情感
        
        Args:
            text (str): 评论文本
        
        Returns:
            tuple: (情感类别, 情感分数)
        """
        if not text or len(text.strip()) == 0:
            return "中性", 0.5
        
        try:
            s = SnowNLP(text)
            score = s.sentiments
            
            if score >= self.sentiment_thresholds["positive"]:
                return "正面", score
            elif score <= self.sentiment_thresholds["negative"]:
                return "负面", score
            else:
                return "中性", score
        except Exception as e:
            print(f"情感分析错误: {e}")
            return "中性", 0.5
    
    def batch_analyze(self, comments_data):
        """
        批量分析评论情感
        
        Args:
            comments_data (list): 评论数据列表
        
        Returns:
            list: 包含情感分析结果的评论数据
        """
        results = []
        
        print(f"开始分析 {len(comments_data)} 条评论...")
        
        for i, comment in enumerate(comments_data):
            if i % 100 == 0:
                print(f"  进度: {i}/{len(comments_data)}")
            
            text = comment.get("content", "")
            sentiment_label, sentiment_score = self.analyze_sentiment(text)
            
            # 添加情感分析结果
            comment_with_sentiment = comment.copy()
            comment_with_sentiment.update({
                "sentiment_label": sentiment_label,
                "sentiment_score": sentiment_score,
                "confidence": abs(sentiment_score - 0.5) * 2  # 置信度
            })
            
            results.append(comment_with_sentiment)
        
        return results
    
    def generate_sentiment_summary(self, analyzed_comments):
        """生成情感分析摘要"""
        sentiments = [c["sentiment_label"] for c in analyzed_comments]
        sentiment_counts = Counter(sentiments)
        
        total = len(analyzed_comments)
        summary = {
            "总评论数": total,
            "情感分布": {
                "正面": sentiment_counts.get("正面", 0),
                "负面": sentiment_counts.get("负面", 0), 
                "中性": sentiment_counts.get("中性", 0)
            },
            "情感比例": {
                "正面比例": round(sentiment_counts.get("正面", 0) / total * 100, 2),
                "负面比例": round(sentiment_counts.get("负面", 0) / total * 100, 2),
                "中性比例": round(sentiment_counts.get("中性", 0) / total * 100, 2)
            },
            "平均情感分数": round(sum(c["sentiment_score"] for c in analyzed_comments) / total, 3)
        }
        
        return summary

def process_single_product(input_file, output_file):
    """处理单个产品的情感分析"""
    analyzer = BasicSentimentAnalyzer()
    
    # 加载数据
    with open(input_file, 'r', encoding='utf-8') as f:
        product_data = json.load(f)
    
    print(f"处理产品: {product_data['product_name']}")
    
    # 进行情感分析
    analyzed_comments = analyzer.batch_analyze(product_data["comments"])
    
    # 生成摘要
    summary = analyzer.generate_sentiment_summary(analyzed_comments)
    
    # 更新产品数据
    product_data["comments"] = analyzed_comments
    product_data["sentiment_summary"] = summary
    
    # 保存结果
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(product_data, f, ensure_ascii=False, indent=2)
    
    print(f"✓ 情感分析完成，保存到: {output_file}")
    print(f"  正面: {summary['情感分布']['正面']} 条 ({summary['情感比例']['正面比例']}%)")
    print(f"  负面: {summary['情感分布']['负面']} 条 ({summary['情感比例']['负面比例']}%)")
    print(f"  中性: {summary['情感分布']['中性']} 条 ({summary['情感比例']['中性比例']}%)")

def main():
    """主处理流程"""
    input_dir = "data/processed"
    output_dir = "results"
    
    # 确保输出目录存在
    os.makedirs(output_dir, exist_ok=True)
    
    # 处理所有产品文件
    for filename in os.listdir(input_dir):
        if filename.endswith('_processed.json'):
            print(f"\n{'='*50}")
            
            input_path = os.path.join(input_dir, filename)
            output_filename = filename.replace('_processed.json', '_sentiment.json')
            output_path = os.path.join(output_dir, output_filename)
            
            process_single_product(input_path, output_path)

if __name__ == "__main__":
    main()